package com.ctrip.ec.api.admin.controller.user;
import com.ctrip.ec.api.admin.common.Encryption;
import com.ctrip.ec.api.admin.common.RequestContext;
import com.ctrip.ec.api.admin.common.ValidateException;
import com.ctrip.ec.api.admin.model.query.QueryModel;
import com.ctrip.ec.api.admin.model.user.LoginModel;
import com.ctrip.ec.biz.dao.agent.AgentDao;
import com.ctrip.ec.biz.dao.role.RoleUserDao;
import com.ctrip.ec.biz.dao.store.StoreDao;
import com.ctrip.ec.biz.dao.user.UserDao;
import com.ctrip.ec.biz.entity.agent.AgentEntity;
import com.ctrip.ec.biz.entity.store.StoreEntity;
import com.ctrip.ec.biz.entity.user.UserEntity;
import com.ctrip.ec.biz.entity.user.UserState;
import com.ctrip.ec.biz.util.RequestUtil;
import com.ctrip.ec.dal.PagerSetting;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController{
    @Autowired
    private UserDao user;

    @Autowired
    private StoreDao store;

    @Autowired
    private RoleUserDao roleUser;

    @Autowired
    private AgentDao agent;

    @GetMapping("list")
    public List<UserEntity> list() throws SQLException {
        List<UserEntity> list = user.list();
        return list;
    }

    @PostMapping("list")
    public List<UserEntity> list(@RequestBody QueryModel model) throws  SQLException{
        PagerSetting setting = model.build();
        List<UserEntity> list = user.list(setting);
        RequestContext.setResponseHeaderCount(setting.getRecordCount());
        return list;
    }

    @GetMapping("detail/{id}")
    public  UserEntity detail(@PathVariable Long id) throws SQLException {
        return user.entity(id);
    }
    @PostMapping("save")
    public  Long save(@RequestBody UserEntity entity) throws Exception {
        if (Strings.isNullOrEmpty(entity.getLoginName())) {
            throw new ValidateException("登录不能为空");
        }

        if (user.exist(entity.getLoginName(), entity.getId())) {
            throw new RuntimeException("用户名已经存在");
        }


        if (entity.getId() == null || entity.getId() == 0) {
            //密码加密
            entity.setPassword(Encryption.md5(entity.getPassword()));
            if (entity.getState() == null) {
                entity.setState(UserState.启用.ordinal());
            }

        } else {
            UserEntity old = user.entity(entity.getId());
            if (old.getPassword().equals(entity.getPassword()) == false) {
                entity.setPassword(Encryption.desEncript(entity.getPassword()));
            }

        }
        user.save(entity);
        return entity.getId();
    }
    @PostMapping("delete")
    public  void delete(@RequestBody List<Long> ids) throws SQLException {
        user.delete(ids);
    }

    @PostMapping("login")
    public  String login(@RequestBody LoginModel loginModel,HttpServletRequest request) throws Exception {

        if(Strings.isNullOrEmpty(loginModel.getLoginName())){
            throw new ValidateException("用户名不能为空");
        }
        if(Strings.isNullOrEmpty(loginModel.getPassword())){
            throw new ValidateException("密码不能为空");
        }


        String token = null;
        String ip = RequestUtil.getClientIp(request);

        UserEntity entity = this.user.entityByLoginName(loginModel.getLoginName());
        if(entity == null){
            throw new ValidateException("用户名不存在");
        }
        if(entity.getState() == UserState.停用.ordinal()){
            throw new ValidateException("用户已停用");
        }
        if(!entity.getPassword().equals(Encryption.md5(loginModel.getPassword()))){
            throw new ValidateException("密码错");
        }
        else{
            Long storeId = 0L;
            StoreEntity storeEntity = store.entityByUserId(entity.getId());
            if(storeEntity != null){
                storeId = storeEntity.getId();
            }

            AgentEntity agentEntity = agent.entityByUserId(entity.getId());
            Long agentId = 0L;
            if(agentEntity!=null){
                agentId= agentEntity.getId();
            }
            token = RequestContext.generateToken(entity.getId(), entity.getName(), ip,storeId,agentId);

        }

        return token;

    }

    @GetMapping("info")
    public  UserEntity info() throws SQLException {
        UserEntity entity= user.entity(RequestContext.getUserId());
        return entity;
    }

    @PostMapping("saveRole")
    public  void saveRole(@RequestBody List<Long> roleIds,@RequestParam Long userId) throws SQLException {
        roleUser.saveByUserId(roleIds,userId);
    }

    @GetMapping("listRole")
    public  List<Long> listRole(@RequestParam Long userId) throws SQLException {
        return roleUser.listByUserId(userId);
    }
}
